package public

import (
	"sync"
	"time"
)

// 流量计数器管理器
var FlowCounterHandler *FlowCounter

type FlowCounter struct {
	RedisFlowCountMap   map[string]*RedisFlowCountService // 服务名 -> 计数器映射
	RedisFlowCountSlice []*RedisFlowCountService          // 计数器列表（保持顺序）
	Locker              sync.RWMutex                      // 读写锁
}

func NewFlowCounter() *FlowCounter {
	return &FlowCounter{
		RedisFlowCountMap:   map[string]*RedisFlowCountService{},
		RedisFlowCountSlice: []*RedisFlowCountService{},
		Locker:              sync.RWMutex{},
	}
}

func init() {
	// 创建全局单例的流量计数器管理器
	FlowCounterHandler = NewFlowCounter()
}

// 获取计数器
func (counter *FlowCounter) GetCounter(serverName string) (*RedisFlowCountService, error) {
	// 1.先在切片中查找现有计数器
	for _, item := range counter.RedisFlowCountSlice {
		if item.AppID == serverName {
			return item, nil
		}
	}

	// 2.找不到则创建新的计数器
	newCounter := NewRedisFlowCountService(serverName, 1*time.Second)

	// 3.添加到数据结构中
	counter.RedisFlowCountSlice = append(counter.RedisFlowCountSlice, newCounter)
	counter.Locker.Lock()
	defer counter.Locker.Unlock()
	counter.RedisFlowCountMap[serverName] = newCounter

	return newCounter, nil
}
